<template>
    <el-dialog v-model="visible" title="预览" :width="width+'mm'" :before-close="handleClose">
        <div v-show="false" v-if="visible">
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-card style="overflow: auto;height: 100vh;">
                        <el-row>
                            <el-col :span="24" class="rect-printElement-types1 hiprintEpContainer1">
                            </el-col>
                        </el-row>
                    </el-card>
                </el-col>
                <el-col :span="15">
                    <el-card class="card-design">
                        <div id="hiprint-printTemplate1" class="hiprint-printTemplate1"></div>
                    </el-card>
                </el-col>
                <el-col :span="5" class="params_setting_container">
                    <el-card class="card-design">
                        <el-row class="hinnn-layout-sider">
                            <div id="PrintElementOptionSetting1"></div>
                        </el-row>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <template #header="{ close, titleId, titleClass }">
            <div style="display: flex;align-items: center;">
              <h4>预览</h4>
              <el-button type="primary" size="small" style="margin-left: 10px;" @click="toPdf">PDF</el-button>
              <el-button type="primary" size="small" @click="print">打印</el-button>
            </div>
          </template>
          <div v-loading="spinning" v-if="visible">
            <div id="preview_content_tasks1"></div>
          </div>
    </el-dialog>
</template>
<script setup>
    import {ref,defineEmits,onMounted} from "vue"
    import {hiprint,hiPrintPlugin} from 'vue-plugin-hiprint'
    import {aProvider} from './providers.js'
    let emit = defineEmits(['itfo'])
    let visible=ref(false)
    let width = ref('210')
    let spinning = ref(true)
    let formTop = ref(null)//主表字段
    let tableButtom = ref(null) //明细表字段
    let hiprintTemplate =ref(null)// 记录实例化打印
    let datalLst = ref(null)
    let formData = ref({})
    let url = ref(null)
    let tableDataList = ref([])
    // 记录ID
    let mobanID = ref(0)
    const itfo=(alltable,list,DataForm,tableData,id,path)=>{
        url.value=path
        
        if(path=='/Print/DY002'){
            tableDataList.value=DataForm
        }else{
            formData.value = DataForm
            formData.value={...formData.value,...tableData}
        }
        
        // visible.value=true
        datalLst.value=list
        if(hiprintTemplate.value&&mobanID.value!=id){
            mobanID.value=id
            // 更新内容
            setTimeout(()=>{
                hiprintTemplate.value.update(list)
                setTimeout(() => {
                    // eslint-disable-next-line no-undef
                    $('#preview_content_tasks1').html(hiprintTemplate.value.getHtml(formData.value))
                    spinning.value = false
                    if(url.value=='/Print/DY002'){
                        tableDataList.value.forEach((item)=>{
                            peintis(item)
                        })
                    }else{
                        peintis(formData.value)
                    }
                }, 100)
            })
            return
        }else if(hiprintTemplate.value&&mobanID.value==id){
            if(url.value=='/Print/DY002'){
                tableDataList.value.forEach((item)=>{
                    peintis(item)
                })
            }else{
                        peintis(formData.value)
                    }
            return
        }
        mobanID.value=id
        width.value=list.panels[0].width
        // 开始处理所有字段成组件可用
        let topList = []
        let buotmList = []
        topList.push({ tid: 'aProviderModule.logo', title: 'Logo', data: '', type: 'image' },)
        alltable.forEach(element => {
            if (element.tableType === 0) {
                element.Fields.forEach((item, index) => {
                    topList.push({
                        tid: item.fieldID, title: item.fieldTitle, data: item.fieldTitle, type: 'text',
                        options: {
                            field: item.fieldName,
                            testData: '测试数据' + index,
                            height: 16,
                            fontSize: 6.75,
                            fontWeight: "700",
                            textAlign: "left",
                            textContentVerticalAlign: "middle"
                        }
                    })
                })
            }else{
                console.log(element);
                let FieldsT = []
                let FieldsC = []
                element.Fields.forEach((item,index)=>{
                    console.log(item);
                    FieldsT.push({ text: item.fieldTitle, field: item.fieldName })
                    FieldsC.push({ title: item.fieldTitle, align: 'center', field: item.fieldName, width: 150 })
                })
                buotmList.push({
                    tid: 'T'+element.tableID, 
                    title: element.tableTitle,
                    type: 'table',
                    options: {
						field: element.tableName,
						tableHeaderRepeat: 'first',
						tableFooterRepeat: 'last',
						fields: FieldsT,
					},
                    editable: true,
					columnDisplayEditable: true,//列显示是否能编辑
					columnDisplayIndexEditable: true,//列顺序显示是否能编辑
					columnTitleEditable: true,//列标题是否能编辑
					columnResizable: true, //列宽是否能调整
					columnAlignEditable: true,//列对齐是否调整
					isEnableEditField: true, //编辑字段
					isEnableContextMenu: true, //开启右键菜单 默认true
					isEnableInsertRow: true, //插入行
					isEnableDeleteRow: true, //删除行
					isEnableInsertColumn: true, //插入列
					isEnableDeleteColumn: true, //删除列
					isEnableMergeCell: true, //合并单元格
                    columns: [FieldsC],
                })
                
            }
        });
        formTop.value = topList
        tableButtom.value= buotmList
        // 以上处理完字段，下方开始实例化打印
        setTimeout(()=>{
            getPrint(formTop.value,tableButtom.value,url.value)
        },500)
    }
    //初始化打印
    const getPrint=(top,but,path)=>{
        console.log(aProvider(formTop.value,tableButtom.value));
        // 初始化打印
        hiprint.init({
            providers: [aProvider(formTop.value,tableButtom.value)]
        });
        $('.hiprintEpContainer1').empty()
        hiprint.PrintElementTypeManager.build('.hiprintEpContainer1', 'taskProviderModule');
        // 还原配置
        hiprint.setConfig()
        // 替换配置
        hiprint.setConfig({
            movingDistance: 2.5,
            text: {
                supportOptions: [
                    {
                        name: 'styler',
                        hidden: true
                    },
                    {
                        name: 'formatter',
                        hidden: true
                    },
                ]
            }
        })
        hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
        console.log(datalLst.value);
        hiprintTemplate.value = new hiprint.PrintTemplate({
            template: datalLst.value,
            settingContainer: '#PrintElementOptionSetting1',
            paginationContainer: '.hiprint-printPagination'
        });
        hiprintTemplate.value.design('#hiprint-printTemplate1');
        setTimeout(()=>{
            $('#preview_content_tasks1').html(hiprintTemplate.value.getHtml(formData.value))
            spinning.value = false
            if(url.value=='/Print/DY002'){
                tableDataList.value.forEach((item)=>{
                    peintis(item)
                })
            }else{
                peintis(formData.value)
            }
            
        })
    }
    // 直接打印
    const peintis = (value)=>{
        
        if (window.hiwebSocket.opened) {
            alert("完成")
            const printerList = hiprintTemplate.value.getPrinterList();
            console.log(printerList)
            hiprintTemplate.value.print2(value, {printer: '', title: 'hiprint测试打印'});
            return
        }
      alert('客户端未连接,无法直接打印')
    }
    let waitShowPrinter = ref(false)
    // 打印
    const print = ()=>{
        // waitShowPrinter.value = true
        // hiprintTemplate.value.print(formData.value, {}, {
        //     callback: () => {
        //         waitShowPrinter.value = false
        //     }
        // })
    }
    // 转PDF
    const toPdf = ()=>{
        hiprintTemplate.value.toPdf(formData.value, '打印预览pdf');
    }
    const handleClose = ()=>{
        console.log('弹窗关闭');
        visible.value=false
        hiprintTemplate.value=null
    }
    defineExpose({
        itfo
    })
</script>